import datetime

from django.contrib import admin
from .models import Type,Note
# Register your models here.

# 创建笔记类型管理类
@admin.register(Type)
class TypeAdmin(admin.ModelAdmin):
    list_display = ['id','name','type_dec']


# 创建笔型管理类
class NoteAdmin(admin.ModelAdmin):
    # 在后台列表页中显示的字段名
    list_display = ['id','title','user','type','pub_date','read_num','like_num','is_delete']
    list_display_links = ['title']
    list_filter = ['user', 'type']
    date_hierarchy = 'pub_date'
    actions_on_bottom = True
    # 在添加笔记的时候显示必要显示的字段名
    fields = ['type','title','content']
    readonly_fields = ('user',)

    # 后台只能查看自己写的笔记
    def get_queryset(self, request):
        qs = super(NoteAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)

    # 保存文章的时候默认的作者是自己
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        # obj.pub_date = datetime.datetime.now()
        # obj.read_num = 0
        # obj.like_num = 0
        obj.save()

    # def get_readonly_fields(self, request, obj=None):
    #     """  重新定义此函数，限制普通用户所能修改的字段  """
    #     if request.user.is_superuser:
    #         self.readonly_fields = []
    #     return self.readonly_fields


admin.site.register(Note,NoteAdmin)
admin.site.site_header = '云笔记后台管理系统'